package pei.lei.lostandfound.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import pei.lei.lostandfound.base.utils.KeyUtil;
import pei.lei.lostandfound.base.utils.NoticeStateCode;
import pei.lei.lostandfound.base.utils.ResultUtil;
import pei.lei.lostandfound.base.dto.ResultDTO;
import pei.lei.lostandfound.base.page.PageList;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import pei.lei.lostandfound.dto.NoticeDTO;
import pei.lei.lostandfound.entity.UserInfo;
import pei.lei.lostandfound.service.NoticeService;
import pei.lei.lostandfound.entity.Notice;
import pei.lei.lostandfound.service.UserInfoService;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 *
 * @author Zhang
 * @since 2021-01-18
 */
@RestController
@RequestMapping("/Notice")
@CrossOrigin
@Slf4j
public class NoticeController {

    @Value("${serverIp}")
    private String serverIp;

    @Value("${file-path}")
    private String filePath;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private NoticeService noticeService;


/*
*  模糊查询（），按照用户id查询，公告id查询
*  创建公告（多文件上传），修改公告（多文件上传），下架公告，举报公告，完成公告
* */

    @PostMapping("/fileTest")
    @ApiOperation("文件上传测试")
    public ResultDTO filesTest(@RequestParam(value="file", required=false) MultipartFile file)throws Exception{
        StringBuffer fileUrls = new StringBuffer();
        if (StringUtils.isNotBlank(file.getOriginalFilename())) {
            //生成随机文件名
            //String fileName = file.getOriginalFilename();
            String fileName = KeyUtil.getUniqueKey()+"."+file.getOriginalFilename().split("\\.")[1];
            log.info(fileName+"文件上传");
            //文件存储路径
            String uploadPath = filePath;
            //文件映射路径
            String serverUploadPath = "http://"+serverIp+"/file/";
            File realFile = new File(uploadPath);
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realFile, fileName));
            log.info(serverUploadPath+fileName+"上传完成");
            fileUrls.append(serverUploadPath+fileName+";");
        }else {
        }
        return ResultUtil.Success(fileUrls.toString());
    }



    @PostMapping("/filesTest")
    @ApiOperation("多文件上传测试")
    public ResultDTO fileTest(@RequestParam(value="files", required=false) MultipartFile[] files)throws Exception{
        StringBuffer fileUrls = new StringBuffer();
        /*try {*/
        if (files != null) {
            for (MultipartFile file : files) {
                if (StringUtils.isNotBlank(file.getOriginalFilename())) {
                    String fileName = file.getOriginalFilename();
                    log.info(fileName+"文件上传");
                    String uploadPath = filePath;
                    String serverUploadPath = "http://"+serverIp+"/file/";
                    log.info(serverUploadPath+fileName+"上传完成");
                    fileUrls.append(serverUploadPath+fileName+";");
                }
            }
        }

      /*  }catch (Exception e){
            return ResultUtil.Error("500",e.getMessage());
        }*/
        return ResultUtil.Success(fileUrls.toString());
    }

    @PostMapping("/releseNotice")
    @ApiOperation("发布公告")
    /*@ApiImplicitParam(name = "files", dataType = "_file", required = false, value = "文件")*/
    public ResultDTO fileTest(Notice notice/*,@RequestParam(value="files", required=false) MultipartFile[] files*/)throws Exception{
        System.out.println("发布公告");
        StringBuffer fileUrls = new StringBuffer();
        Notice save = new Notice();
        notice.setCreatTime(new Date());
        notice.setState(NoticeStateCode.RELEASE);
        System.out.println(notice);
        try {
             save = noticeService.save(notice);
            System.out.println(save);
           /* if (files != null) {
                for (MultipartFile file : files) {
                    if (StringUtils.isNotBlank(file.getOriginalFilename())) {
                        String fileName = notice.getNoticeId()+ "-"+file.getOriginalFilename();
                        log.info(fileName+"文件上传");
                        //String uploadPath = "/project/lost-and-found/file/";
                        String uploadPath = filePath;
                        String serverUploadPath = "http://"+serverIp+"/file/";
                        File realFile = new File(uploadPath);
                        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realFile, fileName));
                        log.info(serverUploadPath+fileName+"上传完成");
                        fileUrls.append(serverUploadPath+fileName+";");
                    }
                }
                save.setFileUrl(fileUrls.toString());
            }else {
                save.setFileUrl("");
            }*/
            //noticeService.save(save);
        }catch (Exception e){
            return ResultUtil.Error("500",e.getMessage());
        }
        return ResultUtil.Success(save);
    }

    @PostMapping("/updateNotice")
    @ApiOperation("更改公告")
    /*@ApiImplicitParam(name = "files", dataType = "_file", required = false, value = "文件")*/
    public ResultDTO updateNotice(Notice notice/*,@RequestParam(value="files", required=false) MultipartFile[] files*/)throws Exception{
        Notice oldNotice = noticeService.get(notice.getNoticeId());
        //StringBuffer fileUrls = new  StringBuffer(oldNotice.getFileUrl());
        try {
            /*if (files != null) {
                for (MultipartFile file : files) {
                    if (StringUtils.isNotBlank(file.getOriginalFilename())) {
                        String fileName = notice.getNoticeId()+ "-"+file.getOriginalFilename();
                        log.info(fileName+"文件上传");
                        String uploadPath = filePath;
                        String serverUploadPath = "http://"+serverIp+"/file/";
                        File realFile = new File(uploadPath);
                        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realFile, fileName));
                        log.info(serverUploadPath+fileName+"上传完成");
                        fileUrls.append(serverUploadPath+fileName+";");
                    }
                }
                notice.setFileUrl(fileUrls.toString());
            }*/
            noticeService.update(notice);
        }catch (Exception e){
            return ResultUtil.Error("500",e.getMessage());
        }
        return ResultUtil.Success(noticeService.get(notice.getNoticeId()));
    }


        @GetMapping("{id}")
        @ApiOperation("按公告id查找数据")
        public ResultDTO get(@PathVariable("id") String id)throws Exception{
            Notice notice = null;
            NoticeDTO noticeDTO;
            try {
                notice = noticeService.get(id);
                UserInfo userInfo = userInfoService.get(notice.getUserId());
                noticeDTO = new NoticeDTO(notice, userInfo);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(noticeDTO);
        }

        @GetMapping("/selectByUserId/{id}")
        @ApiOperation("按用户id查找数据")
        public ResultDTO getByUserId(@PathVariable("id") String userId)throws Exception{
            ArrayList<NoticeDTO> resultList = new ArrayList<>();
            Notice notice = new Notice();
            try {
                notice.setUserId(userId);
                List<Notice> noticeList = noticeService.findByParams(notice,"creat_time desc");
                UserInfo userInfo = userInfoService.get(userId);
                for (Notice item : noticeList) {
                    resultList.add(new NoticeDTO(item,userInfo));
                }
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(resultList);
        }


        @GetMapping("/FuzzyQuery/{message}")
        @ApiOperation("模糊查询公告")
        public ResultDTO FuzzyQuery(@PathVariable("message") String message){
            List<NoticeDTO> resultList = null;
            try {
                log.info(message);
                resultList = noticeService.FuzzyQuery(message);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(resultList);
        }


        @PostMapping("/newNotice")
        @ApiOperation("查看除了下架了的的公告，按照发布时间排序")
        @ApiImplicitParams({
                @ApiImplicitParam( name = "pageNum", dataType = "Integer", defaultValue = "1", required = false, value = "页码"),
                @ApiImplicitParam( name = "pageSize", dataType = "Integer", defaultValue = "10", required = false, value = "每页容量")
        })
        public ResultDTO getNewNotice(@RequestParam(value = "pageNum", defaultValue = "1", required=false ) int pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10", required=false )int pageSize) throws Exception{
            PageList<NoticeDTO> dtoPageList = null;
            try {
                dtoPageList =noticeService.getNewNotice(pageNum, pageSize);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(dtoPageList);
        }

        @PostMapping("/insertNotice")
        @ApiOperation(value = "插入一条数据")
        //@ApiImplicitParams()
        public ResultDTO insertOne(@RequestBody Notice notice)throws Exception{
            try {
                noticeService.save(notice);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(notice);
        }

        @PostMapping("/updateById")
        @ApiOperation(value = "按id修改数据")
        //@ApiImplicitParams()
        public ResultDTO updateById(@RequestBody Notice notice)throws Exception{
            try {
                noticeService.update(notice);
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(noticeService.get(notice.getNoticeId()));

        }


        @GetMapping("/deleteById/{id}")
        @ApiOperation("按id删除数据")
        @ApiImplicitParams({
                @ApiImplicitParam(paramType = "path", name = "id", dataType = "string", required = true, value = "实体类id"),

        })
        public ResultDTO deleteById(@PathVariable("id") String id)throws Exception{
            Notice oldNotice = null;
            try {
                oldNotice = noticeService.get(id);
                noticeService.deleteById(Long.parseLong(id));
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(oldNotice);
        }

        @PostMapping("/getNoticePage")
        @ApiOperation("按条件查询，分页")
        @ApiImplicitParams({
                @ApiImplicitParam(paramType = "query", name = "pageNum", dataType = "Integer", defaultValue = "1", required = false, value = "页码"),
                @ApiImplicitParam(paramType = "query", name = "pageSize", dataType = "Integer", defaultValue = "10", required = false, value = "每页容量")
        })
        public ResultDTO selectEntityPage(@RequestBody Notice notice,
                                          @RequestParam(value = "pageNum", defaultValue = "1", required=false ) int pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10", required=false )int pageSize) throws Exception{

            PageList<NoticeDTO> resultPageData = null;
            try {
                PageList<Notice> papageData = noticeService.findPageData(notice, pageNum, pageSize,"creat_time desc");
                List<Notice> noticeList = papageData.getData();
                List<NoticeDTO> resultList = new ArrayList<>();
                for (Notice item : noticeList) {
                    UserInfo userInfo = userInfoService.get(item.getUserId());
                    resultList.add(new NoticeDTO(item,userInfo));
                    resultPageData = new PageList<>(resultList,papageData.getPageNum(),papageData.getPageSize(),papageData.getTotalItems());
                }
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(resultPageData);

        }

        @PostMapping("/getNotice")
        @ApiOperation("按条件查询，不分页")
        //@ApiImplicitParams()
        public ResultDTO selectEntityPage(@RequestBody Notice notice)throws Exception{
            List<NoticeDTO> resultList = new ArrayList<>();
            try {
                List<Notice> noticeList = noticeService.findByParams(notice,"creat_time desc");
                for (Notice item : noticeList) {
                    UserInfo userInfo = userInfoService.get(item.getUserId());
                    resultList.add(new NoticeDTO(item, userInfo));
                }
            } catch (Exception e) {
                return ResultUtil.Error("500",e.getMessage());
            }
            return ResultUtil.Success(resultList);
        }


}
